//
//  JZStoreValue.m
//  tf02
//
//  Created by Jim on 16/8/22.
//  Copyright © 2016年 Jim. All rights reserved.
//

#import "JZStoreValue.h"
#import "FastCoder.h"

static JZStoreValue *storeValue = nil;

@implementation JZStoreValue

+ (instancetype)shareInstance {
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        storeValue = (JZStoreValue *)@"JZStoreValue";
        storeValue = [[JZStoreValue alloc] init];
    });
    
//    防止子类使用
    NSString *classString = NSStringFromClass([self class]);
    if ([classString isEqualToString:@"JZStoreValue"] == NO) {
        NSParameterAssert(nil); //若使用执行到这里就会崩溃
    }
    return storeValue;
}

- (instancetype)init {
    NSString *string = (NSString *)storeValue;
    if ([string isKindOfClass:[NSString class]] == YES && [string isEqualToString:@"JZStoreValue"]) {
        if (self = [super init]) {
//            防止子类使用
            NSString *classString = NSStringFromClass([self class]);
            if (![classString isEqualToString:@"JZStoreValue"]) {
                NSParameterAssert(nil);
            }
        }
        
        return self;
    } else {
        
        return nil;
    }
}

- (void)storeValue:(id)value withKey:(NSString *)key {
    NSParameterAssert(value);
    NSParameterAssert(key);
    
    NSData *data = [FastCoder dataWithRootObject:value];
    if (data) {

        @synchronized (self) {
            [[NSUserDefaults standardUserDefaults] setObject:data forKey:key];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }
}

- (id)valueWithKey:(NSString *)key {
    
    NSParameterAssert(key);
    
    NSData *data = [[NSUserDefaults standardUserDefaults] valueForKey:key];

    return [FastCoder objectWithData:data];
}

@end



























